package com.chap17.completablefuture;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * <p>
 * <code>Demo03</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-05-08 15:38
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class Demo03 {
    public static void main(String[] args) throws InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();

            }
            if (new Random().nextInt(10) % 2 == 0) {
                int i = 12 / 0;
            }
            System.out.println("执行结束！");
            return "test";
        });

        //Consumer影响结果，会消费结果 参数s就是结果
        //所以这个whenComplete不用 get或者join
        future.whenComplete(new BiConsumer<String, Throwable>() {
            @Override
            public void accept(String s, Throwable throwable) {
                System.out.println(s+" 执行完成！");
            }
        });

        //Function不会消费结果，要拿到异常还需要join
        future.exceptionally(new Function<Throwable, String>() {
            @Override
            public String apply(Throwable throwable) {
                System.out.println("执行失败："+ throwable.getMessage());
                return "异常";
            }
        }).join();

    }
}

//出现异常 exceptionally会执行
//whenComplete也会执行，只不过拿不到结果
